package com.example.tool.action;

import com.example.tool.module.ModulePInformation;
import com.example.tool.ui.ConfigDialogWrapper;
import com.example.tool.utils.AES;
import com.example.tool.utils.FileUtil;
import com.example.tool.utils.WebServersUtil;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import org.jetbrains.annotations.NotNull;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

/**
 * <p>Title: ShowTipsActions</p >
 * Description: 配置操作
 * <p>CreateTime: 2022/6/28 11:20</p>
 * @author FT
 */
public class ConfigActions extends AnAction {
  private static final Logger LOG = Logger.getInstance(ConfigActions.class);

  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    Project project = e.getProject();
    if (project != null) {
      ConfigDialogWrapper configDialogWrapper = new ConfigDialogWrapper(project);
      // 按下ok按键
      if (configDialogWrapper.showAndGet()) {
        String text = configDialogWrapper.getTextFieldWithBrowseButton().getText();
        String pluginId = configDialogWrapper.getPluginID().getText();
        String pluginStaticDirectory = configDialogWrapper.getStaticDirectory().getText();
        String[] information = ActionUtil.getInformation(project);
        try {
          String uuid;
          if (information != null) {
            try {
              uuid = information[3];
            } catch (Exception exception) {
              uuid = UUID.randomUUID().toString();
            }
          } else {
            uuid = UUID.randomUUID().toString();
          }
          String txt = text + "|" + pluginId + "|" + pluginStaticDirectory + "|" + uuid;
          String rest = AES.encryption(ModulePInformation.MODULE_SECRET_KEY, txt);
          URL resource = new URL("file:///" + project.getBasePath() + "/.idea/" + ModulePInformation.MODULE_CONFIG);
          String count = FileUtil.readFilePath(resource, false);
          if (!rest.equals(count)) {
            FileUtil.generateFile(project.getBasePath() + "/.idea/" + ModulePInformation.MODULE_CONFIG, AES.encryption(ModulePInformation.MODULE_SECRET_KEY, txt));
          }
          String finalUuid = uuid;
          if (information != null) {
            // 不存在或与原先的值不相等
            if (!text.equals(information[0]) || FileUtil.isHave(project.getBasePath() + "/.idea/webServers.xml")) {
              FileUtil.generateFile(project.getBasePath() + "/.idea/webServers.xml", "/.idea/webServers.xml",
                  str -> WebServersUtil.changeConfiguration(str, text, finalUuid));
            }
            if (!pluginStaticDirectory.equals(information[2]) || FileUtil.isHave(project.getBasePath() + "/.idea/deployment.xml")) {
              FileUtil.generateFile(project.getBasePath() + "/.idea/deployment.xml", "/.idea/deployment.xml",
                  str -> str.replace("$pluginCategory$", "STOOL"));
              UpdateDeployment(project, pluginStaticDirectory, LOG);
            }
          } else {
            FileUtil.generateFile(project.getBasePath() + "/.idea/webServers.xml", "/.idea/webServers.xml",
                str -> WebServersUtil.changeConfiguration(str, text, finalUuid));
            FileUtil.generateFile(project.getBasePath() + "/.idea/deployment.xml", "/.idea/deployment.xml",
                str -> str.replace("$pluginCategory$", "STOOL"));
            UpdateDeployment(project, pluginStaticDirectory, LOG);
          }
          LocalFileSystem.getInstance().refresh(true);
        } catch (MalformedURLException ex) {
          ex.printStackTrace();
        }
      }
    }
  }

  // 更新deployment.xml 配置文件才能生效
  public static void UpdateDeployment(Project project, String pluginStaticDirectory, Logger log) {
    new Thread(() -> {
      try {
        log.info("SeeyonTool Update deployment.xml file start");
        Thread.sleep(10000);
        FileUtil.generateFile(project.getBasePath() + "/.idea/deployment.xml", "/.idea/deployment.xml",
            str -> str.replace("$pluginCategory$", pluginStaticDirectory));
        LocalFileSystem.getInstance().refresh(true);
        log.info("SeeyonTool Update deployment.xml file end");
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      }
    }).start();
  }
}
